package com.apes.scm.stock.safetyStock.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.repository.ProductUomRepository;
import com.apes.scm.stock.safetyStock.model.SafetyStockGap;
import com.apes.scm.stock.safetyStock.repository.SafetyStockGapRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service("safetyStockGapService")
public class SafetyStockGapService extends DomainService {
    @Autowired
    private SafetyStockGapRepository safetyStockGapRepository;
    @Autowired
    private ProductUomRepository productUomRepository;

    public void create(SimpleRequest request) {

    }

    public void save(SafetyStockGap safetyStockGap) {
        safetyStockGapRepository.save(safetyStockGap);
    }

    // 修改分配数量
    public void updateAssignedQty(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        SafetyStockGap safetyStockGap = safetyStockGapRepository.findOne(getJO.getLong("id"));

        ProductUom dumpUom = productUomRepository.findAll(JpaDsl.toCriteriaByEq("uomCategory.id", safetyStockGap.getProduct().getId(), "transferFirst", true)).get(0);
        double changeAssignedQty = changeQty(dumpUom, safetyStockGap.getProduct().getUom(), getJO.getDoubleValue("assignedQty"));

        safetyStockGap.setAssignedQty(safetyStockGap.getAssignedQty() + changeAssignedQty);
        this.save(safetyStockGap);
    }

    // 数量转换
    private double changeQty(ProductUom currentUom, ProductUom convertThisUom, double qty) {
        return Math.floor(currentUom.computeQty(qty, convertThisUom, false));
    }
























































}
